import React from "react";
import {
    ActivityIndicator,
    Alert,
    DeviceEventEmitter,
    InteractionManager,
    ListView,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import chjStyle from "../../CustomStyle";
import ModuleCommonHeader from "../module/ModuleCommonHeader";
import BaseInfo from "./cias/BaseInfo";
import CarListItem from "./common/CarListItem";
import {Actions} from "react-native-router-flux";
import Util from "../Util";
import {connect} from "react-redux";
import {setLoadingState} from "../../redux/action/homePage.js";

class RecordedCarList extends React.Component {
    // 构造函数，可执行初始化操作
    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            isLoading: true,
            dataSource: ds.cloneWithRows([]),
            modalVisible: false
        };
        this._uploadData = this._uploadData.bind(this);
        this.onImageUploadSuccess = this.onImageUploadSuccess.bind(this);
        this.onImageUploadFailed = this.onImageUploadFailed.bind(this);
    }

    // 组件被加载时
    componentDidMount() {
        this.updateEventListener = DeviceEventEmitter.addListener('update', (v) => this.notifyUpdate());
        InteractionManager.runAfterInteractions(() => {
            Util.storage.load({
                key: 'carjson',
                id: '1000'
            }).then(ret => {
                Util.parseCarJson(ret);

                this.setState({
                    isLoading: false,
                });
                this.notifyUpdate();
            }).catch(err => {
                let carJson = require('../../../configs/dataLite.json');
                Util.parseCarJson(carJson);
                carJson = null;

                this.setState({
                    isLoading: false,
                });
                this.notifyUpdate();
            });
        });
    }

    // 组件即将被卸载时
    componentWillUnmount() {
        this.updateEventListener.remove();
    }

    notifyUpdate() {
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        Util.storage.getAllDataForKey('cars').then(
            cars => this.setState({
                dataSource: ds.cloneWithRows(cars.reverse())
            })
        );
    }

    renderRow(rowData) {
        return (<CarListItem object={rowData}
                             accredit={false}
                             onClickedListener={() => this.clickedItem(rowData)}
                             onClickedUploadListener={() => this.clickedUpload(rowData)}
                             onClickedQAListener={() => this.clickedQA(rowData)}
                             onClickedDeleteListener={() => this.clickedDelete(rowData)}
        />)
    }

    clickedItem(rowData) {
        Util.selectCar = rowData;
        Actions.BaseInfo(
            {
                name: 'BaseInfo',
                component: BaseInfo,
            }
        );
    }

    clickedUpload(rowData) {
        this._setDialog([
            {name: '寄售', value: '100'},
            {name: '认证', value: '200'},
            {name: '拍卖', value: '300'}
        ], (item, index) => {
            this._uploadData(rowData, item.value);
        });
    }

    _uploadData(rowData, value) {
        // 设置基本信息的type，并保存数组
        rowData.basicinfo.type = {name: '', value: value};
        Util.saveData('cars', rowData);

        this.props.setLoading(true, '上传图片中...');
        this.timer = setTimeout(
            () => {
                this.timer && clearTimeout(this.timer);
                Util.uploadImages(rowData, () => {
                    console.log('RecordedCarList  success');
                    this.onImageUploadSuccess(rowData);
                }, (err) => {
                    console.log('RecordedCarList failed ');
                    this.onImageUploadFailed(err)
                });
            }, 500
        );
    }

    onImageUploadSuccess(rowData) {
        // 把表征里程赋值到基本信息里
        rowData.basicinfo.travelkilometer.value = rowData.carconfig[1].value;
        const user = Util.getUser();
        let params = {
            token: user.token,
            userid: user.id,
            basicinfo: Util.makeBasicParams(rowData),
            expandinfo: Util.makeExpandParams(rowData, Util.checkQainfo(rowData) === Util.OK),
            carid: rowData.carid ? rowData.carid : '0',
        };
        this.props.setLoading(true, '上传数据中...');
        console.log('RecordedCarList onImageUploadSuccess ');
        Util.postServer('user/issuecarinfo', params, (result) => {
            this.onDataUploadSuccess(rowData, result)
        }, (msg) => this.onDataUploadFailed(msg));
    }

    onImageUploadFailed(err) {
        this.props.setLoading(false, '');
        Util.showToast('上传图片失败[' + err + ']');
    }

    onDataUploadSuccess(rowData, result) {
        console.log('RecordedCarList onDataUploadSuccess ');
        this.props.setLoading(false, '');
        if (result.status === '0' || result.status === 0) {
            Util.showToast('车辆数据上传成功');
            rowData.carid = result.data.carid;
            Util.saveData('cars', rowData);
            this.notifyUpdate();
        } else {
            Util.showToast('上传数据失败:' + result.msg);
        }
    }

    onDataUploadFailed(msg) {
        this.props.setLoading(false, '');

        Util.showToast('上传数据失败[' + msg + ']');

    }

    clickedQA(rowData) {
        Actions.QaRoot({
            saveKey: 'cars',
            saveData: rowData,
        });
    }

    clickedDelete(rowData) {
        Alert.alert(
            '确认删除吗？',
            '车辆数据一旦删除就无法找回了',
            [
                {
                    text: '取消', onPress: () => {
                }
                },
                {text: '确认删除', onPress: () => this.deleteCarData(rowData)},
            ]
        );
    }

    deleteCarData(rowData) {
        Util.storage.remove(
            {
                key: 'cars',
                id: rowData.saveId
            }
        );
        this.notifyUpdate();
    }

    // 组件被渲染时
    render() {
        if (this.state.isLoading) {

            return (
                <View style={chjStyle.mainContainer}>
                    <ModuleCommonHeader title='已录入车辆' clickedLeft={this.clickedBack.bind(this)} leftText='返回'
                                        clickedRight={this.clickedNew.bind(this)} rightText='新增'/>
                    <ActivityIndicator
                        animating={true}
                        style={{alignItems: 'center', justifyContent: 'center', height: chjStyle.height}}
                        size="large"/>
                </View>
            );
        }
        return (
            <View style={chjStyle.mainContainer}>
                <ModuleCommonHeader title='已录入车辆' clickedLeft={this.clickedBack.bind(this)} leftText='返回'
                                    clickedRight={this.clickedNew.bind(this)} rightText='新增'/>
                <ListView
                    initialListSize={5}
                    dataSource={this.state.dataSource}
                    renderRow={(rowData) => this.renderRow(rowData)}
                    style={chjStyle.mainList}>
                </ListView>
                <TouchableOpacity
                    onPress={() => this.requestCheckVersion()}
                    style={{
                        position: 'absolute',
                        backgroundColor: '#ff971d',
                        left: 0,
                        top: chjStyle.height - chjStyle.footerHeight,
                        width: chjStyle.width,
                        height: chjStyle.footerHeight,
                    }}>
                    <Text style={{
                        backgroundColor: 'rgba(0,0,0,0)',
                        color: '#fff',
                        textAlign: 'center',
                        top: chjStyle.getActualSizeInVertical(36),
                        fontSize: chjStyle.getActualFontSize(30)
                    }}>更新车型数据</Text>
                </TouchableOpacity>
            </View>
        );
    }

    requestCheckVersion() {
        this.props.setLoading(true, '检查更新..');
        fetch(Util.server + 'json/version.json')
            .then((response) => response.text())
            .then((responseText) => {
                let result = JSON.parse(responseText);
                let version = result.version;
                Util.storage.load({
                    key: 'version',
                    id: '1000'
                }).then(ret => {
                    this.props.setLoading(false, '');
                    if (ret.version !== result.version) {
                        this.requestUpdateData(result);
                    } else {
                        Util.showToast('车型数据已经是最新版');
                    }
                }).catch(err => {
                    this.props.setLoading(false, '');
                    this.requestUpdateData(result);
                });
            })
            .catch(function (error) {
                Util.showToast(error);
            })
            .done();
    }

    requestUpdateData(versionData) {
        this.props.setLoading(true, '同步数据中');
        fetch(Util.server + 'json/dataLite.json')
            .then((response) => response.text())
            .then((responseText) => {
                let result = JSON.parse(responseText);
                Util.storage.save({
                    key: 'carjson',
                    id: '1000',
                    rawData: result,
                    expires: null
                });
                Util.storage.save({
                    key: 'version',
                    id: '1000',
                    rawData: versionData,
                    expires: null
                });

                Util.parseCarJson(result);
                this.props.setLoading(false, '');
                Util.showToast('数据已经更新到最新版');
            })
            .catch(function (error) {
                this.props.setLoading(false, '');
                Util.showToast(error);
            })
            .done();
    }

    clickedBack() {
        Actions.pop();
    }

    clickedNew() {
        Util.selectCar = null;
        Actions.BaseInfo();
    }

    _setDialog(array, select) {
        Actions.dialog({
            array,
            select,
        });
    }
}

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {
        setLoading: (loading, text) => {
            dispatch(setLoadingState(loading, text));
        },
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(RecordedCarList);